import React, { useEffect, useState } from 'react'
import { useLocation, useNavigate } from "react-router-dom";
import axios from 'axios'
import { Layout, Menu } from 'antd';
import "./SideMenu.css"
import {
    PieChartOutlined,
    MailOutlined,
    AppstoreOutlined,
    SoundOutlined,
    FileSearchOutlined,
    GlobalOutlined
} from '@ant-design/icons';
const { Sider } = Layout;
export default function SideMenu(props) {
    const location = useLocation();
    const { collapsed } = props;
    //定义一个图标对象
    const menuIcon = {
        "/home": <PieChartOutlined />,
        "/user-manage": <MailOutlined />,
        "/right-manage": < AppstoreOutlined />,
        "/news-manage": <SoundOutlined />,
        "/audit-manage": <FileSearchOutlined />,
        "/publish-manage": <GlobalOutlined />


    }
    const [menu, setMenu] = useState([])
    const handleMenuData = (data) => {
        for (var i = 0; i < data.length; i++) {
            var item = data[i]
            if (item.children) {
                item.icon = menuIcon[item.key];
                if (item.children.length === 0) {
                    item.children = undefined;
                } else {
                    handleMenuData(item.children)
                }
            }
            if (!item.pagepermisson) {
                data.splice(i--, 1)
            }
        }
        return data;
    }
    useEffect(() => {
        axios.get("http://192.168.2.3:3000/rights?_embed=children")
            .then(res => {
                //处理返回数据， 如果children是空就不加该key
                setMenu(handleMenuData(res.data))
            });
        return () => { }
    }, []);


    const navigate = useNavigate()
    function getItem(label, key, icon, children, type) {
        return {
            key,
            icon,
            children,
            label,
            type,
        };
    }


    const selectedKeys = location.pathname;
    const openKeys = "/" + location.pathname.split("/")[1];

    return (
        <Sider trigger={null} collapsible collapsed={collapsed}>

            <div style={{ display: "flex", height: "100%", flexDirection: "column" }}>
                <div className="logo">EIMP</div>
                <div style={{ flex: 1, overflow: "auto" }}>
                    <Menu
                        defaultOpenKeys={[openKeys]}
                        theme="dark"
                        mode="inline"
                        defaultSelectedKeys={[selectedKeys]}
                        inlineCollapsed={true}
                        items={menu}
                        onClick={(e) => (navigate(e.key))}
                    />
                </div>

            </div>
        </Sider>
    )
}
